package study.wechat.applet.client.token;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import study.wechat.applet.client.WechatHttp;

import java.util.Map;

/**
 * 获取接口调用凭据
 * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
 */
@Slf4j
@Component
public class TokenClient {

    private static final String PATH = "/cgi-bin/token";

    @Value("${wechat.applet.appId}")
    private String appId;
    @Value("${wechat.applet.appSecret}")
    private String appSecret;

    public TokenInfo getAccessToken() {
        //
        Map<String, Object> param = Maps.newHashMap();
        param.put("appid", appId);
        param.put("secret", appSecret);
        param.put("grant_type", "client_credential");
        //
        String body = WechatHttp.get(PATH, param);
        TokenInfo info = JSONUtil.toBean(body, TokenInfo.class);
        return info;
    }
}
